package com.becca.cake.controller.address;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.becca.cake.core.common.BaseAction;
import com.becca.cake.core.common.PagingBean;
import com.becca.cake.core.exception.CommonExceptionHandle;
import com.becca.cake.model.address.CityModel;
import com.becca.cake.model.address.ProvinceModel;
import com.becca.cake.model.address.RegionModel;
import com.becca.cake.model.users.UserAddressModel;
import com.becca.cake.service.address.IAddressService;
import com.becca.cake.util.JsonUtil;
import com.becca.cake.util.StringUtil;

/**
 * 地址管理
 * @copyright  尊星(上海)信息科技有限公司
 * @author yellow
 * @date 2016年5月23日 上午11:58:00
 */
@Controller
@RequestMapping("/addressManager")
public class AddressAction extends BaseAction {
    private final static Log logger = LogFactory.getLog(AddressAction.class);

    @Autowired
    private IAddressService  iAddressService;

    /**
     * 加载省
     * @return
     */
    @RequestMapping(value = "/queryProvince", method = RequestMethod.GET)
    @ResponseBody
    public String queryProvince() {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<ProvinceModel> list = this.iAddressService.queryProvinces(map);
            return JsonUtil.writeObjectNoPageJSON(list);
        } catch (Exception e) {
            logger.error("加载省失败!", e);
            return JsonUtil.returnJsonUnSuccess("加载省失败!");
        }
    }

    /**
     * 根据省ID加载市
     * @return
     */
    @RequestMapping(value = "/queryCitysByProvinceId", method = RequestMethod.GET)
    @ResponseBody
    public String queryCitysByProvinceId(@RequestParam(value = "provinceId", required = false) String provinceId) {
        if (StringUtil.isNotEmpty(provinceId)) {
            try {
                List<CityModel> list = this.iAddressService.queryCitysByProvinceId(provinceId);
                return JsonUtil.writeObjectNoPageJSON(list);
            } catch (Exception e) {
                logger.error("获取城市集合失败!");
                return JsonUtil.returnJsonUnSuccess("获取城市集合失败!");
            }
        } else {
            logger.error("获取城市时省ID为空!");
            return JsonUtil.returnJsonUnSuccess("获取城市时省ID为空!");
        }
    }

    /**
     * 根据市ID加载区县
     * @return
     */
    @RequestMapping(value = "/queryRegionsByCityId", method = RequestMethod.GET)
    @ResponseBody
    public String queryRegionsByCityId(@RequestParam(value = "cityId", required = false) String cityId) {
        if (StringUtil.isNotEmpty(cityId)) {
            try {
                List<RegionModel> list = this.iAddressService.queryRegionsByCityId(cityId);
                return JsonUtil.writeObjectNoPageJSON(list);
            } catch (Exception e) {
                logger.error("获取区县集合失败!");
                return JsonUtil.returnJsonUnSuccess("获取区县集合失败!");
            }
        } else {
            logger.error("获取区县时市ID为空!");
            return JsonUtil.returnJsonUnSuccess("获取区县时市ID为空!");
        }
    }

    /**
     * 根据用户Id查询地址列表
     * @return
     */
    @RequestMapping(value = "/selectAddressByUserId", method = RequestMethod.POST)
    @ResponseBody
    public String selectAddressByUserId(@RequestParam Integer userId, @RequestParam Integer status) {
        Map<String, Object> map = new HashMap<String, Object>();
        PagingBean page = getInitPagingBean();
        map.put("pagingBean", page);
        map.put("userId", userId);
        map.put("status", status);
        if (userId != null) {
            try {
                List<UserAddressModel> list = this.iAddressService.selectAddressByUserId(map);
                Long count = this.iAddressService.selectUserAddressCount(map);
                return JsonUtil.writeObjectPageJSON(list, count);
            } catch (Exception e) {
                logger.error("获取地址失败!");
                return JsonUtil.returnJsonUnSuccess("获取地址失败!");
            }
        } else {
            logger.error("获取地址时用户编号为空!");
            return JsonUtil.returnJsonUnSuccess("获取地址时用户编号为空!");
        }
    }

    /**
     * 修改用户地址状态
     * @param id
     * @param status
     * @return
     */
    @RequestMapping(value = "/updateAdressStatus", method = RequestMethod.POST)
    @ResponseBody
    public String updateAdressStatus(@RequestParam Integer id, @RequestParam Integer status) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("status", status);
        map.put("userName", this.getUserSeesion().getName());
        try {
            this.iAddressService.updateAdressStatus(map);
            return JsonUtil.returnJsonSuccess("删除成功！");
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }

    /**
     * 修改是否默认地址
     * @param id
     * @param status
     * @return
     */
    @RequestMapping(value = "/updateAdressDefault", method = RequestMethod.POST)
    @ResponseBody
    public String updateAdressDefault(@RequestParam Integer id, @RequestParam Integer isDefault) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("isDefault", isDefault);
        map.put("userName", this.getUserSeesion().getName());
        try {
            this.iAddressService.updateAdressDefault(map);
            return JsonUtil.returnJsonSuccess("删除成功！");
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }

    /**
     * 添加或修改用户地址信息
     * @author yellow
     * @return
     */
    @RequestMapping(value = "/addOrUpdUserAddress", method = RequestMethod.POST)
    @ResponseBody
    public String addOrUpdUserAddress(UserAddressModel userAddressModel) {
        userAddressModel.setCreatedName(this.getUserSeesion().getTrueName());
        userAddressModel.setUpdatedName(this.getUserSeesion().getTrueName());
        userAddressModel.setStatus(UserAddressModel.ADDRESS_STATUS_ENABLE);
        try {
            this.iAddressService.addOrUpdUserAddress(userAddressModel);
            return JsonUtil.returnJsonSuccess("操作地址信息成功!");
        } catch (Exception e) {
            return JsonUtil.returnJsonUnSuccess(CommonExceptionHandle.handleException(e));
        }
    }

    /**
     * 根据id查询用户地址对象
     * @param id
     * @param status
     * @return
     */
    @RequestMapping(value = "/selectUserAddressById", method = RequestMethod.POST)
    @ResponseBody
    public String selectUserAddressById(@RequestParam Integer id) {
        if (id != null) {
            try {
                UserAddressModel userAddressModel = this.iAddressService.selectUserAddressById(id);
                return JsonUtil.writeObjectFormJSON(userAddressModel);
            } catch (Exception e) {
                logger.error("获取地址失败!");
                return JsonUtil.returnJsonUnSuccess("获取地址失败!");
            }
        } else {
            logger.error("获取地址时用户编号为空!");
            return JsonUtil.returnJsonUnSuccess("获取地址时地址编号为空!");
        }
    }
}
